//
//  gxdy_AddressBookManager.m
//  OCQ_API_Test
//
//  Created by 故乡的云  on 2017/5/4.
//  Copyright © 2017年 故乡的云 . All rights reserved.
//

#import "gxdy_AddressBookManager.h"
//#import <Contacts/Contacts.h> // ios9.0 +
#import <AddressBook/AddressBook.h>  // ios9.0 -
//#import "gxdy_Contact.h"

@implementation gxdy_AddressBookManager

+ (instancetype)manager {
    gxdy_AddressBookManager *book = [[self alloc] init];
    [self requestAuthorizationForAddressBook];
    return book;
}

/** 获取权限 */
+ (void)requestAuthorizationForAddressBook {
    // ios 版本判断
    CGFloat ios_ver = [[[UIDevice currentDevice] systemVersion] floatValue];
    gxdy_Log(@"ios_version:%0.1f",ios_ver);
    if (ios_ver > 9.0) { // ios < 9.0
#warning iOS 9.0之前版本授权 没有测试
        // 判断是否授权
        ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();
        if(authorizationStatus == kABAuthorizationStatusDenied) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请求通讯录权限失败" message:@"需如开启，请到“系统设置”-->“OCQ” 开启！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }else if (authorizationStatus != kABAuthorizationStatusAuthorized) {
            // 请求授权
            ABAddressBookRef addressBookRef = ABAddressBookCreate();
            ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
                if (granted) { // 授权成功
                    
                } else {  // 授权失败
                    NSLog(@"授权失败！");
                    
                }
            });
        }
    }else { // ios 9.0 +
        CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        if(authorizationStatus == CNAuthorizationStatusDenied) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请求通讯录权限失败" message:@"需如开启，请到“系统设置”-->“OCQ” 开启！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }else if (authorizationStatus != CNAuthorizationStatusAuthorized) {
            CNContactStore *contactStore = [[CNContactStore alloc] init];
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    
                } else {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请求通讯录权限" message:@"请求授权失败！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alertView show];
                }
            }];
        }
    }
}


/*!
 * @描述 获取本地联系人，会自动调用-requestAuthorizationForAddressBook 方法获取授权.
 *
 * @参数 keysToFetch：指定要获取的联系人属性。可以传nil，表示所有属性;
 *
 * @返回值 返回CNContact对象数组，CNContact对象的属性值取决于keysToFetch中的keys.
 */
+ (NSArray <gxdy_Contact *>*)getAddressBookWithKeysToFetch:(NSArray <id<CNKeyDescriptor>>*)keysToFetch {
    [self requestAuthorizationForAddressBook]; // 获取授权
    __block NSMutableArray *contacts = [NSMutableArray array];
    CGFloat ios_ver = [[[UIDevice currentDevice] systemVersion] floatValue];
    
    if (ios_ver < 9.0) { // ios < 9.0
        // 获取所有联系人
        ABAddressBookRef addressBookRef = ABAddressBookCreate();
        CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
        long count = CFArrayGetCount(arrayRef);
        for (int i = 0; i < count; i++) {
            // 获取联系人对象的引用
            ABRecordRef recordRef = CFArrayGetValueAtIndex(arrayRef, i);
            gxdy_Contact *contact = [gxdy_Contact contactWithRecordRef:recordRef];
            [contacts addObject:contact];
        }
    }else {
        
        // 指定具体需要的字段
        if (keysToFetch == nil) {
            //        keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
            keysToFetch = @[ // all keys
                            CNContactPropertyNotFetchedExceptionName,
                            CNContactIdentifierKey,
                            CNContactNamePrefixKey,
                            CNContactGivenNameKey,
                            CNContactMiddleNameKey,
                            CNContactFamilyNameKey,
                            CNContactPreviousFamilyNameKey,
                            CNContactNameSuffixKey,
                            CNContactNicknameKey,
                            CNContactOrganizationNameKey,
                            CNContactDepartmentNameKey,
                            CNContactJobTitleKey,
                            CNContactPhoneticGivenNameKey,
                            CNContactPhoneticMiddleNameKey,
                            CNContactPhoneticFamilyNameKey,
                            CNContactPhoneticOrganizationNameKey,
                            CNContactBirthdayKey,
                            CNContactNonGregorianBirthdayKey,
                            CNContactNoteKey,
                            CNContactImageDataKey,
                            CNContactThumbnailImageDataKey,
                            CNContactImageDataAvailableKey,
                            CNContactTypeKey,
                            CNContactPhoneNumbersKey,
                            CNContactEmailAddressesKey,
                            CNContactPostalAddressesKey,
                            CNContactDatesKey,
                            CNContactUrlAddressesKey,
                            CNContactRelationsKey,
                            CNContactSocialProfilesKey,
                            CNContactInstantMessageAddressesKey
                            ];
        }
        
        CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) { //    *stop = YES; // 停止遍历，相当于break；
            
            [contacts addObject:[gxdy_Contact contactWithContact:contact]];
            /*
             NSString *givenName = contact.givenName;
             NSString *familyName = contact.familyName;
             NSArray *phoneNumbers = contact.phoneNumbers;
             NSLog(@"givenName：%@, familyName：%@", givenName, familyName);
             for (CNLabeledValue *labelValue in phoneNumbers) {
             NSString *label = labelValue.label;
             CNPhoneNumber *phoneNumber = labelValue.value;
             
             NSLog(@"label：%@, phone：%@", label, phoneNumber.stringValue);
             
             }
             */
        }];
    }
    
    return contacts;
}
@end
